﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Example04.aspx.cs" Inherits="Chapter33.Example04" %>

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>代码清单 33-4 手动收集和发送数据</title>
    <meta name="author" content="Adam Freeman" />
    <meta name="description" content="A simple example" />
    <link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
    <style>
        .table {
            display: table;
        }

        .row {
            display: table-row;
        }

        .cell {
            display: table-cell;
            padding: 5px;
        }

        .label {
            text-align: right;
        }
    </style>
</head>
<body>
    <form id="fruitform" action="http://localhost:8080/form" method="post">
        <div class="table">
            <div class="row">
                <div class="cell label">Bananas:</div>
                <div class="cell">
                    <input type="number" name="bananas" value="2" />
                </div>
            </div>
            <div class="row">
                <div class="cell label">Apples:</div>
                <div class="cell">
                    <input type="number" name="apples" value="5" />
                </div>
            </div>
            <div class="row">
                <div class="cell label">Cherries:</div>
                <div class="cell">
                    <input type="number" name="cherries" value="20" />
                </div>
            </div>
            <div class="row">
                <div class="cell label">Total:</div>
                <div class="cell" id="results">0 items</div>
            </div>
        </div>
        <button id="submit" type="submit">Submit Form</button>
    </form>
    <script>
        document.getElementById('submit').onclick = handleButtonPress;

        function handleButtonPress(e) {
            e.preventDefault();
            var form = document.getElementById('fruitform');
            var formData = '';
            var inputElements = document.getElementsByTagName('input');
            for (var i = 0; i < inputElements.length; i++) {
                formData += inputElements[i].name + '=' + inputElements[i].value + '&';
            }
            var httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = handleResponse;
            httpRequest.open('POST', form.action);
            httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            httpRequest.send(formData);
        }

        function handleResponse(e) {
            if (e.target.readyState == XMLHttpRequest.DONE && e.target.status == 200) {
                document.getElementById('results').innerHTML = e.target.responseText;
            }
        }
    </script>
</body>
</html>
